package com.ruoyi.service.file.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.service.file.entity.FileContentEntity;
import com.ruoyi.service.file.mapper.FileContentMapper;
import com.ruoyi.service.file.service.FileContentService;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 内容文件信息表 服务实现类
 * </p>
 *
 * @author Zane
 * @since 2025-10-10
 */
@Service
public class FileContentServiceImpl extends ServiceImpl<FileContentMapper, FileContentEntity>
    implements FileContentService {

  @Override
  public FileContentEntity saveFileContent(String fileName, String fileUrl, String contentJson,
      Long userId) {
    String key = MD5.create().digestHex(StrUtil.format("{} {}", userId, fileUrl));
    FileContentEntity fileContentEntity = new FileContentEntity()
        .setFileData(contentJson)
        .setFilePath(fileUrl)
        .setFileName(fileName)
        .setFileKey(key)
        .setCreateTime(LocalDateTime.now())
        .setCreateBy(userId);
    this.save(fileContentEntity);
    return fileContentEntity;
  }

  @Override
  public List<FileContentEntity> listByFileKeys(List<String> fileKeys) {
    final LambdaQueryWrapper<FileContentEntity> query = effectQuery()
        .in(FileContentEntity::getFileKey, fileKeys);
    return list(query);
  }

  @Override
  public FileContentEntity selectByFileKey(String fileKey) {
    final LambdaQueryWrapper<FileContentEntity> query = effectQuery()
        .eq(FileContentEntity::getFileKey, fileKey);
    return getOne(query);
  }

  private LambdaQueryWrapper<FileContentEntity> effectQuery() {
    return new LambdaQueryWrapper<>();
  }
}
